import reqwest from 'reqwest'

import * as Api from '../../api/Api'

export const REQUEST_ARTICLES = 'REQUEST_ARTICLES'
export const RECEIVE_ARTICLES = 'RECEIVE_ARTICLES'

export function fetchArticles(id) {
	return (dispatch, getState) => {
		const state = getState()
		dispatch({
			type: 'REQUEST_ARTICLES'
		})

		let articles = state.get('articles')

		let query = {
			version_id: articles.get('query').get('version_id'),
			channel_id: id,
			user_id: articles.get('query').get('user_id'),
			limit: articles.get('query').get('limit'),
			page: articles.get('query').get('channel_id') == id ? articles.get('query').get('page') : 1
		}

		reqwest({
			url: Api.getArticles,
			method: 'post',
			data: query,
			success: function(data) {
				let articleData = articles.get('query').get('channel_id') == id ? articles.get('datas').toJS() : []
				dispatch({
					type: 'RECEIVE_ARTICLES',
					articles: articleData.concat(JSON.parse(data).databody),
					query: Object.assign({}, query, {
						page: query.page + 1
					})
				})
			}
		})
	}
}